<?php

/*
 * This file is part of the FOSUserBundle package.
 *
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Gds\UserBundle\Controller;

use Symfony\Component\DependencyInjection\ContainerAware;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use FOS\UserBundle\Model\UserInterface;
use JMS\SecurityExtraBundle\Annotation\Secure;

/**
 * Controller managing the password change
 *
 * @author Thibault Duplessis <thibault.duplessis@gmail.com>
 * @author Christophe Coevoet <stof@notk.org>
 */
class ChangePasswordController extends ContainerAware {

    /**
     * @Secure(roles="ROLE_ADMIN")
     */
    public function changePasswordAction() {
        $admin = $this->container->get('security.context')->getToken()->getUser();
        if (!is_object($admin) || !$admin instanceof UserInterface) {

            throw new AccessDeniedException('This user does not have access to this section.');
        }
        $form = $this->container->get('fos_user.change_password.form');
        $formHandler = $this->container->get('fos_user.change_password.form.handler');
        $process = $formHandler->process();
        $response = array();
        if ($process) {
            $response['success'] = true;
            return new \Symfony\Component\HttpFoundation\Response(json_encode($response));
        }
        if ($this->container->get('request')->isMethod('post')) {
            $response['success'] = false;
            $response['contenu'] = $this->container->get('templating')->render(
                    'GdsUserBundle:ChangePassword:changePassword.html.' . $this->container->getParameter('fos_user.template.engine'), array('form' => $form->createView())
            );
            return new \Symfony\Component\HttpFoundation\Response(json_encode($response));
        }

        return $this->container->get('templating')->renderResponse(
                        'GdsUserBundle:ChangePassword:changePassword.html.' . $this->container->getParameter('fos_user.template.engine'), array('form' => $form->createView())
        );
    }

    /**
     * Generate the redirection url when the resetting is completed.
     *
     * @param \FOS\UserBundle\Model\UserInterface $user
     *
     * @return string
     */
    protected function getRedirectionUrl(UserInterface $user) {
        return $this->container->get('router')->generate('fos_user_profile_show');
    }

    /**
     * @param string $action
     * @param string $value
     */
    protected function setFlash($action, $value) {
        $this->container->get('session')->getFlashBag()->set($action, $value);
    }

}
